package cn.myspringboot.user.controller;

import cn.myspringboot.anno.PreAuthorize;
import cn.myspringboot.user.domain.User;
import cn.myspringboot.user.query.UserQuery;
import cn.myspringboot.user.service.UserService;
import cn.myspringboot.utils.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Api("User相关的接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PreAuthorize(name = "根据id查询用户信息",sn = "user:findById",descs ="根据id查询用户信息")
    @ApiOperation("根据id查询用户信息")
    @GetMapping("/{id}")
    public R findById(@PathVariable("id")Long id){
        return R.ok(userService.findById(id));
    }

    @PreAuthorize(name = "查询所有用户信息",sn = "user:findAll",descs ="查询所有用户信息")
    @ApiOperation("查询所有用户信息")
    @GetMapping
    public R findAll(){
        return R.ok(userService.findAll());
    }

    @PreAuthorize(name = "根据id删除用户信息",sn = "user:deleteById",descs ="根据id删除用户信息")
    @ApiOperation("根据id删除用户信息")
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable("id")Long id){
        userService.deleteById(id);
        return R.ok();
    }

    @PreAuthorize(name = "批量删除用户信息",sn = "user:batchDelete",descs ="批量删除用户信息")
    @ApiOperation("批量删除用户信息")
    @PostMapping("/deleteAll")
    public R batchDelete(@RequestBody List<Long> ids){
        userService.batchDelete(ids);
        return R.ok();
    }

    @PreAuthorize(name = "添加或者修改用户信息",sn = "user:add",descs ="添加或者修改用户信息")
    @ApiOperation("添加或者修改用户信息")
    @PostMapping
    public R add(@RequestBody User user){
        if(user.getId() == null){
            userService.add(user);
        }else {
            userService.update(user);
        }
        return R.ok();
    }

    @PreAuthorize(name = "分页查询用户信息",sn = "user:page",descs ="分页查询用户信息")
    @ApiOperation("分页查询用户信息")
    @PostMapping("/getPage")
    public R page(@RequestBody UserQuery query){
        PageHelper.startPage(query.getPage(), query.getSize());
        List<User> page = userService.getUserByPage(query);
        PageInfo<User> pageInfo = new PageInfo<>(page);
        return R.ok(pageInfo);
    }
}